<template>
    <view class="container">
        <!-- 顶部标题栏 -->
        <view class="header">
            <text class="title">第 {{ roundNumber }} 局结算</text>
            <view class="divider"></view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
            <uni-load-more status="loading"></uni-load-more>
        </view>
        
        <!-- 错误提示 -->
        <view v-if="error" class="error-state">
            <image src="@/static/logo.png" class="error-icon"></image>
            <text class="error-text">{{ error }}</text>
            <button class="retry-button" @click="initData">重试</button>
        </view>

        <!-- 主要内容区域 -->
        <view v-if="!loading && !error" class="content">
            <!-- 玩家结算卡片列表 -->
            <view class="player-cards">
                <view v-for="(member, index) in members" :key="userId" class="player-card">
                    <!-- 玩家头像和信息 -->
                    <view class="player-info">
                        <image :src="member.avatar || defaultAvatar" class="avatar"></image>
                        <text class="player-name">{{ member.nickname }}</text>
                        <text class="role-tag" v-if="currentSettlement.scores[userId]?.isWinner">赢家</text>
                    </view>
                    
                    <!-- 分数输入区域 -->
<!--                    <view class="score-section">
                        <text class="score-label">得分:</text>
                        <input 
                            type="number" 
                            v-model="player.score" 
                            placeholder="0"
                            class="score-input"
							@focus="clearIfDefault(player)"
							@blur="restoreDefault(player)"
                            @input="validateScore(player)"
                            :disabled="player.userId !== currentUserId || isSubmitting" 
                            :class="{ 'disabled-input': player.userId !== currentUserId }"
                        />
                    </view> -->
                    <!-- 分数输入区域（核心优化：直接绑定计算属性） -->
                    <view class="score-section">
                        <text class="score-label">得分:</text>
                        <input 
                            type="number" 
                            v-model="getUserScore(userId)"  
                            placeholder="0"
                            class="score-input"
                            @focus="handleScoreFocus(userId)"
                            @blur="handleScoreBlur(userId)"
                            :disabled="userId !== currentUserId || isSubmitting || isSelfSubmitted" 
                            :class="{ 'disabled-input': userId !== currentUserId }"
                        />
                    </view>
					
                    <!-- 赢家选择 -->
<!--                    <view class="winner-section" v-if="player.userId === currentUserId || player.isWinner">
                        <text class="winner-label">赢家:</text>
                        <switch 
                            :checked="player.isWinner" 
                            @change="handleWinnerChange(player.userId, $event.detail.value)"
                            color="#07C160"
                            class="winner-switch"
                            :disabled="isSubmitting"
                        />
                    </view> -->
					
					
                    <!-- 赢家选择 -->
                    <view class="winner-section" v-if="userId === currentUserId || getUserWinnerStatus(userId)">
                        <text class="winner-label">赢家:</text>
                        <switch 
                            :checked="getUserWinnerStatus(userId)" 
                            @change="(e) => handleWinnerChange(userId, e.detail.value)"
                            color="#07C160"
                            :disabled="isSubmitting || isSelfSubmitted"
                        />
                    </view>
					
					
					
					
                </view>
            </view>
            
            <!-- 结算说明 -->
            <view class="settlement-info">
                <text class="info-text">结算规则：赢家获得所有非赢家支付的分数总和，非赢家支出与自身得分等额的分数</text>
            </view>
            
            <!-- 底部操作栏 -->
<!--            <view class="action-bar">
                <button class="action-button secondary" @click="backbutton" :disabled="isSubmitting">
                    <text>取消</text>
                </button>
                
                <button 
                  class="action-button primary" 
                  @click="confirmbutton" 
                  :disabled="isSubmitting || !allScoresFilled || !hasWinner" 
                >
                  <template v-if="!isSubmitting">
                    <text v-if="allScoresFilled && hasWinner">确认结算</text>
                    <text v-else>请完成结算信息</text>
                  </template>
                  <text v-else>提交中...</text>
                </button>
            </view> -->
			<view class="action-bar">
                <button 
                  class="action-button primary" 
                  @click="confirmbutton" 
                  :disabled="isSubmitting || !allScoresFilled || !hasWinner || isSelfSubmitted" 
                >
                    <template v-if="!isSubmitting">
                        <text v-if="isSelfSubmitted">等待中({{ submittedCount }}/{{ totalCount }})</text>
                        <text v-else-if="allScoresFilled && hasWinner">确认结算</text>
                        <text v-else>请完成结算信息</text>
                    </template>
                    <text v-else>提交中...</text>
                </button>
            </view>
			
			
			
			
			
			
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onUnmounted, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { useSocketStore } from '@/stores/modules/socketStore.js';

// 默认头像
const defaultAvatar = 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png';
// 状态管理实例
const socketStore = useSocketStore();
// 从 socketStore 中解构所需的响应式状态
const { 
	connectionState, 
	roomData } = storeToRefs(socketStore);
// 响应式数据
const loading = ref(true);         // 加载状态
const error = ref(null);           // 错误信息
const isSubmitting = ref(false);   // 提交状态,用于控制按钮显示
const roundNumber = ref(0);        // 当前回合数？
const roomId = ref('');            // 房间ID？
const currentUserId = ref('');     // 当前用户ID————缓存起来？直接从缓存取









//计算属性——————————这里应该直接在store里面封装成getter方法   在外部直接调用方法读取

// 直接从roomData获取当前房间数据
const currentRoom = computed(() => roomData.value[roomId.value] || {});
// 房间成员（直接使用roomData中的members）
const members = computed(() => currentRoom.value.members || {});
const currentSettlement = computed(() => currentRoom.value.currentSettlement || {
  roundNumber: 0,
  submittedUsers: [],
  scores: {},
  isCompleted: false
});

// 已提交人数
const submittedCount = computed(() => currentSettlement.value.submittedUsers.length);
// 房间总人数
const totalCount = computed(() => Object.keys(members.value).length);
// 自己是否已提交
const isSelfSubmitted = computed(() => currentSettlement.value.submittedUsers.includes(currentUserId.value));
const allScoresFilled = computed(() => {
  return Object.keys(members.value).every(userId => {
    const score = currentSettlement.value.scores[userId]?.score;
    return score && !isNaN(parseInt(score));
  });
});
const hasWinner = computed(() => {
  return Object.values(currentSettlement.value.scores).some(item => item?.isWinner);
});

// 提交按钮文本（动态变化）
const submitButtonText = computed(() => {
  if (settlement.value.isCompleted) return "全部已提交";
  if (isSelfSubmitted.value) return `等待中(${submittedCount.value}/${totalCount.value})`;
  return "确认提交";
});



// 优化点1：用计算属性直接绑定分数（替代scoreInputs）
const getUserScore = (userId) => {
  // 读取：从全局状态获取分数
  return computed({
    get: () => {
      return currentSettlement.value.scores[userId]?.score || "0";
    },
    // 写入：直接更新全局状态，同时进行验证
    set: (newValue) => {
      if (userId !== currentUserId.value) return; // 只有自己能修改
      
      // 验证逻辑
      let validated = newValue.replace(/[^\d]/g, '');
      if (!validated) validated = "0";
      if (parseInt(validated) > 500) validated = "500";
      
      // 直接更新全局状态
      currentSettlement.value.scores[userId] = {
        ...currentSettlement.value.scores[userId],
        score: validated
      };
    }
  });
};

// 优化点2：获取赢家状态的工具函数
const getUserWinnerStatus = (userId) => {
  return currentSettlement.value.scores[userId]?.isWinner || false;
};

// 焦点处理（替代之前的clearIfDefault/restoreDefault）
const handleScoreFocus = (userId) => {
  if (userId !== currentUserId.value) return;
  // 聚焦时如果是默认0，清空输入框
  if (getUserScore(userId).value === "0") {
    getUserScore(userId).value = "";
  }
};

const handleScoreBlur = (userId) => {
  if (userId !== currentUserId.value) return;
  // 失焦时如果为空，重置为0
  if (!getUserScore(userId).value) {
    getUserScore(userId).value = "0";
  }
};






















/**
 * 初始化数据 - 从 socketStore.roomData 获取玩家信息（核心修正点）
 */
const initData = async () => {
  try {
    loading.value = true;
    error.value = null;
    
    // 1. 获取当前用户ID
    const userStr = uni.getStorageSync('user') || '{}';
    const user = JSON.parse(userStr);
    currentUserId.value = user.userinfo?.userid || '';
    
    // 2. 从 socketStore.roomData 获取当前房间数据
    const currentRoomData = roomData.value[roomId.value];
	console.log("currentRoomData",currentRoomData)//当前房间对应数据：member、history
	console.log(currentRoomData.members)
    if (!currentRoomData || !currentRoomData.members) {
      throw new Error('房间数据不存在，请重新进入房间');
    }
    // 关键：初始化当前回合的结算状态
        if (roomData.value[roomId.value]) {
          roomData.value[roomId.value].settlement = {
            currentRound: roundNumber.value,  // 当前是第几局
            submittedUsers: [],
            scores: {},
            isCompleted: false
          };
        }
        // 初始化输入框（基于成员列表）
        Object.keys(members.value).forEach(userId => {
              scoreInputs.value[userId] = "0"; // 默认0分
        });
    
        // 4. 注册Socket事件监听
        registerSocketListeners();
    	
      } catch (err) {
        error.value = err.message || '加载数据失败，请稍后重试';
        console.error('初始化数据出错:', err);
      } finally {
        loading.value = false;
      }
    };
    
 //    // 3. 转换全局状态数据为结算页面所需格式————这里二次赋值  是否破坏了响应式?  roomdata更新play会更新吗  好像是会的 找下是在哪里跟新的  因为加载到新进房间的人的分数狂了   那是从用户列表中过来的？
	// //————答：当新用户加入，要刷新才能显示，刷新会重新加载currentRoomData，当用户加入时候更新了currentRoomData
 //    players.value = Object.values(currentRoomData.members).map(member => ({
 //      userId: member.user_id,       // 注意：与 socketStore 中成员数据的字段保持一致（原数据中是 user_id）
 //      nickname: member.nickname,    // 从全局成员数据获取
 //      avatar: member.avatar,        // 从全局成员数据获取
 //      score: "0",                   // 初始化分数
 //      isWinner: false               // 初始化赢家状态
 //    }));    
    
	
	
	
	
	
	

/**
 * 注册Socket事件监听
 */
const registerSocketListeners = () => {
  // 监听其他玩家的分数和赢家状态更新
  socketStore.on('score_updated', (data) => {
    if (data.room_id !== roomId.value || data.roundNumber !== roundNumber.value) return;
    
    const { user_id, score, isWinner } = data;
    const player = players.value.find(p => p.userId === user_id);
    
    if (player && user_id !== currentUserId.value) {
      player.score = score.toString();
      player.isWinner = isWinner;
    }
  });
  // 监听其他玩家的结算数据更新
  socketStore.on('roundpay_update', (data) => {
    if (data.room_id !== roomId.value || data.roundNumber !== roundNumber.value) return;
    // 更新其他玩家的数据，保留自己的数据不变
    players.value = players.value.map(player => {
      const remotePlayer = data.players.find(p => p.userId === player.userId);
      if (remotePlayer && player.userId !== currentUserId.value) {
        return {
          ...player,
          score: remotePlayer.score,
          isWinner: remotePlayer.isWinner
        };
      }
      return player;
    });
  });
  // 监听结算完成事件————给后端使用
  socketStore.on('settlement_completed', (data) => {
    if (true) {
    // if (data.room_id === roomId.value && data.roundNumber === roundNumber.value) {
      uni.showToast({ title: '本局结算已完成' });
      setTimeout(() => uni.navigateBack(), 1500);
    }
  });


	// 在registerSocketListeners中新增监听
	socketStore.on('player_submitted', (data) => {
	  if (data.room_id === roomId.value && data.roundNumber === roundNumber.value) {
		submissionStatus.value[data.user_id] = true;
		updateButtonState();
	  }
	});

	socketStore.on('final_submission', () => {
	  if (!isSubmitting.value) {
		realSubmitToBackend(); // 实际提交到后端
	  }
	});



 // 新增：监听其他人提交的分数，更新本地显示
  socketStore.on('user_score_submitted', (data) => {
    if (data.room_id !== roomId.value || data.roundNumber !== roundNumber.value) return;
    
    const { user_id, score, isWinner } = data;
    const player = players.value.find(p => p.userId === user_id);
    
    if (player) {
      player.score = score;
      player.isWinner = isWinner;
    }
  });
  
  // 新增：监听全部完成事件，自动跳转
  socketStore.on('settlement_all_completed', (data) => {
    if (data.room_id === roomId.value && data.roundNumber === roundNumber.value) {
      uni.showToast({ title: '所有人已提交，正在结算...' });
      setTimeout(() => uni.navigateBack(), 1500);
    }
  });
  
  
};

/**
 * 页面加载时初始化
 */
onLoad((options) => {
  roomId.value = options.roomId;
  roundNumber.value = parseInt(options.roundNumber) || 0;
  
  // 检查Socket连接状态
  if (connectionState.value !== 'connected' || !socketStore.isConnectedToRoom(roomId.value)) {
    socketStore.connect(roomId.value).then(initData);
  } else {
    initData();
  }
  
  // 监听 socketStore 中房间成员变化
  // watch(() => roomData.value[roomId.value]?.members, (newMembers) => {
  //   if (newMembers && !isSubmitting.value) {
  //     // 保留已输入的分数和赢家状态
  //     const currentScores = players.value.reduce((acc, p) => {
  //       acc[p.userId] = { score: p.score, isWinner: p.isWinner };
  //       return acc;
  //     }, {});
      
  //     // 合并新的成员列表和已有分数
  //     players.value = Object.values(newMembers).map(member => ({
  //       userId: member.user_id,  // 注意字段一致性：user_id
  //       nickname: member.nickname,
  //       avatar: member.avatar,
  //       ...(currentScores[member.user_id] || { score: "0", isWinner: false })
  //     }));
  //   }
  // }, { deep: true });
});

/**
 * 分数输入验证与同步
 */
const validateScore = (player) => {
  // 输入验证
  player.score = player.score.replace(/[^\d]/g, '');
  if (!player.score) player.score = "0";
  const num = parseInt(player.score) || 0;
  if (num > 500) player.score = '500';
  // 同步到其他玩家
  // if (player.userId === currentUserId.value) {
  //   socketStore.emit('score_updated', {
  //     room_id: roomId.value,
  //     roundNumber: roundNumber.value,
  //     user_id: currentUserId.value,
  //     score: player.score,
  //     isWinner: player.isWinner
  //   });
    
  // }
};
//分数默认
const clearIfDefault = (player) => {
  if (player.score === "0") player.score = "";
};
const restoreDefault = (player) => {
  if (player.score === "") player.score = "0";
};



/**
 * 最终提交：  计算属性：是否所有分数都已填写
 */
// const allScoresFilled = computed(() => {
//   return players.value.every(player => {
//     const score = parseInt(player.score);
//     return player.score !== '' && !isNaN(score) && score >= 0;
//   });
// });

/**
 * 最终提交：   计算属性：是否已选择赢家
 */
// const hasWinner = computed(() => {
//   return players.value.some(p => p.isWinner);
// });


// 在分数或赢家状态变化时发送更新
const emitRoundpayUpdate = () => {
  socketStore.emit('roundpay_update', {
    room_id: roomId.value,
    roundNumber: roundNumber.value,
    players: players.value.map(p => ({
      userId: p.userId,
      score: p.score,
      isWinner: p.isWinner
    }))
  });
};
/**
 * 赢家状态改变与同步
 */
// 赢家状态切换
const handleWinnerChange = (userId, isWinner) => {
  if (userId !== currentUserId.value) return;

  // 重置其他人的赢家状态
  Object.keys(members.value).forEach(id => {
    currentSettlement.value.scores[id] = {
      ...currentSettlement.value.scores[id],
      isWinner: false
    };
  });

  // 设置当前用户的赢家状态和分数
  currentSettlement.value.scores[userId] = {
    ...currentSettlement.value.scores[userId],
    isWinner,
    score: isWinner ? "20" : currentSettlement.value.scores[userId]?.score || "0"
  };
};




/**
 * 提交结算数据
 */
const confirmbutton = async () => {
  try {
    isSubmitting.value = true;

    if (!allScoresFilled.value) {
      uni.showToast({ title: '请填写所有玩家分数', icon: 'none' });
      return;
    }
    if (!hasWinner.value) {
      uni.showToast({ title: '请选择一个赢家', icon: 'none' });
      return;
    }
	

	
	
	// 获取当前用户的分数数据————————————————————————————这里吧play直接去掉，不要中间再倒腾一下  直接用store里面的数据
	// 广播当前用户的分数
    socketStore.emit('user_score_submitted', {
      room_id: roomId.value,
      roundNumber: roundNumber.value,
      user_id: currentUserId.value,
      score: getUserScore(currentUserId.value).value,
      isWinner: getUserWinnerStatus(currentUserId.value)
    });
	
    // 2. 检查是否是最后一个提交的人
    const newSubmittedCount = submittedCount.value + 1; // +1是因为自己刚提交
    if (newSubmittedCount === totalCount.value) {
      // 最后一个人负责提交到后端
      await submitToBackend();
    } else {
      // 不是最后一个，只显示等待
      uni.showToast({ title: `已提交，等待其他${totalCount.value - newSubmittedCount}人` });
    }
  } catch (err) {
    console.error('提交失败:', err);
    uni.showToast({ title: err.message || '提交失败', icon: 'none' });
  } finally {
    isSubmitting.value = false;
  }
};
	

const submitToBackend = async () => {
  try {
    // 收集所有人的分数
    const allScores = settlement.value.scores;
    const res = await uni.request({
      url: 'http://172.16.24.120:5000/mysqlroom/rounds/settle',
      method: 'POST',
      data: {
        roomId: roomId.value,
        roundNumber: roundNumber.value,
        players: Object.entries(allScores).map(([userId, data]) => ({
          userId,
          score: parseInt(data.score),
          isWinner: data.isWinner
        }))
      }
    });
    
    if (res.statusCode === 200) {
      // 广播给所有人：全部提交完成   这里前端监听 后端广播就行了
      socketStore.emit('settlement_all_completed', {
        room_id: roomId.value,
        roundNumber: roundNumber.value
      });
    } else {
      throw new Error('保存到服务器失败');
    }
  } catch (err) {
    console.error('最终提交失败:', err);
    uni.showToast({ title: '结算失败，请重试', icon: 'none' });
  }
};


























/**
 * 返回按钮处理
 */
const backbutton = () => {
  // uni.navigateBack();
  // emitRoundpayUpdate();
  console.log(players.value)
  console.log(currentUserId.value)
  console.log(isSubmitting.value)

};

/**
 * 组件卸载时清理
 */
onUnmounted(() => {
  socketStore.off('score_updated');
  socketStore.off('settlement_completed');
});

/**
 * 监听Socket连接状态变化
 */
watch(connectionState, (newState) => {
  if (newState === 'disconnected' && !loading.value && !error.value) {
    error.value = '连接已断开，请重试';
  }
});
</script>

<style scoped>
/* 全局容器样式 */
.container {
    padding: 0;
    background-color: #f8f8f8;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}
/* 头部样式 */
.header {
    padding: 20px 16px 12px;
    background-color: #ffffff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.title {
    font-size: 20px;
    font-weight: 600;
    color: #333;
    text-align: center;
}

.divider {
    height: 1px;
    background-color: #eee;
    margin-top: 12px;
}

/* 加载状态样式 */
.loading-state {
    padding: 40px 0;
    display: flex;
    justify-content: center;
}

/* 错误状态样式 */
.error-state {
    padding: 40px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.error-icon {
    width: 60px;
    height: 60px;
    margin-bottom: 16px;
}

.error-text {
    font-size: 16px;
    color: #ff4d4f;
    margin-bottom: 20px;
    text-align: center;
}

.retry-button {
    background-color: #1890ff;
    color: white;
    border: none;
    border-radius: 20px;
    padding: 8px 24px;
    font-size: 14px;
}

/* 主要内容区域 */
.content {
    flex: 1;
    padding: 16px;
    display: flex;
    flex-direction: column;
}

/* 结算说明 */
.settlement-info {
    padding: 12px 16px;
    background-color: #fff8e6;
    border-radius: 8px;
    margin: 10px 0;
}

.info-text {
    font-size: 14px;
    color: #e6a23c;
    line-height: 1.5;
}

/* 玩家卡片列表 */
.player-cards {
    flex: 1;
}

.player-card {
    background-color: #fff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.player-info {
    display: flex;
    align-items: center;
    flex: 1;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 12px;
}

.player-name {
    font-size: 16px;
    color: #333;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100px;
}

.role-tag {
    background-color: #07C160;
    color: white;
    font-size: 12px;
    padding: 2px 8px;
    border-radius: 12px;
    margin-left: 8px;
}

/* 分数输入区域 */
.score-section {
    display: flex;
    align-items: center;
    margin: 0 16px;
}

.score-label {
    font-size: 14px;
    color: #666;
    margin-right: 8px;
}

.score-input {
    width: 80px;
    height: 36px;
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 0 10px;
    text-align: center;
    font-size: 16px;
    color: #333;
    background-color: #f9f9f9;
}

/* 赢家选择区域 */
.winner-section {
    display: flex;
    align-items: center;
}

.winner-label {
    font-size: 14px;
    color: #666;
    margin-right: 8px;
}

.winner-switch {
    transform: scale(0.8);
}

/* 底部操作栏 */
.action-bar {
    display: flex;
    justify-content: space-between;
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #eee;
    position: sticky;
    bottom: 0;
}

.action-button {
    flex: 1;
    height: 48px;
    border-radius: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s;
}

.action-button.secondary {
    background-color: #f5f5f5;
    color: #666;
    margin-right: 12px;
}

.action-button.secondary:active {
    background-color: #e5e5e5;
}

.action-button.primary {
    background-color: #07C160;
    color: white;
}

.action-button.primary:disabled {
    background-color: #a0d7b8;
    opacity: 0.7;
}

.action-button.primary:active:not(:disabled) {
    background-color: #05a14e;
}

/* 非当前用户的输入框样式 */
.disabled-input {
  background-color: #f0f0f0;
  color: #999;
  cursor: not-allowed;
}
</style>
